<template>
  <div class="category-wrapper">
    <div class="top">
      <div class="title-wrapper">
        <div class="title">商品分类</div>
      </div>
      <el-button type="primary" @click.native="add">添加</el-button>
    </div>
    <div class="content">
      <table-list ref="tableList" :list="list" @deleteItem="handleDeleteItem" @confirm="handleConfirm" />
    </div>
  </div>
</template>
<script>
import TableList from './category/tableList'
import { getCategoryList } from '@/api/category'
const ERR_OK = 200
export default {
  components: {
    TableList
  },
  data() {
    return {
      list: []
    }
  },
  mounted() {
    this._getCategoryList()
  },
  methods: {
    add() {
      this.$refs.tableList.add()
    },
    delItem(scope) {
      const id = scope.row.id
      // 根据一级查找并删除一级
      if (scope.row.children) {
        const fIndex = this.list.findIndex((item, index) => {
          return item.id === id
        })
        if (fIndex >= 0) {
          this.list.splice(fIndex, 1)
        }
      } else {
        // 根据二级找一级并删除
        let oIndex
        let fIndex
        for (let i = 0; i <= this.list.length - 1; i++) {
          fIndex = this.list[i].children.findIndex((secItem, secIndex) => {
            return secItem.id === id
          })
          if (fIndex >= 0) {
            oIndex = i
            break
          }
        }
        this.list[oIndex].children.splice(fIndex, 1)
      }
    },
    handleDeleteItem(scope) {
      this.delItem(scope)
    },
    handleConfirm() {
      this._getCategoryList()
    },
    _getCategoryList() {
      getCategoryList()
        .then(res => {
          if (res.code === ERR_OK) {
            console.log(res)
            const list = this._replaceKey(res.data, 'lower', 'children')
            this.list = list
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    _replaceKey(arr, oldKey, newKey) {
      arr.forEach((item, index) => {
        while (item[oldKey]) {
          item[newKey] = item[oldKey]
          delete item[oldKey]
        }
      })
      return arr
    }
  }

}
</script>
<style lang="scss" scoped>
@import "@/styles/el-button.scss";
.category-wrapper {
  padding: 0 20px;
  box-sizing: border-box;
  padding-bottom: 50px;
  // min-height: 105vh;
  .top {
    width: 100%;
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;
    .title-wrapper {
      display: flex;
      align-content: center;
      .title {
        height: 44px;
        line-height: 44px;
        color: rgba(68, 68, 68, 1);
        font-size: 18px;
        font-family: Roboto;
        font-weight: bold;
        cursor: pointer;
      }
    }
  }
}

</style>
